package middleware

import (
	"fmt"
	"gitee.com/zr233/bsf/errors"
	"github.com/ZR233/goutils/stackx"
	"github.com/gin-gonic/gin"
)

func Recover() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if p := recover(); p != nil {
				var (
					stdErr *errors.StandardError
					ok     = false
				)

				if stdErr, ok = p.(*errors.StandardError); !ok {
					stdErr = errors.NewFromError(fmt.Errorf("%s", p), errors.ErrorCode_Unknown)
				}
				stdErr.File = string(stackx.Stack(0))

				_ = c.Error(stdErr)
			}
		}()

		c.Next()
	}
}
